<?php
/**
 * User_Notification
 *
 * Класс User_Notification осуществляет работу по оповещению пользователей о различных событиях
 *
 * @author Егоров Александр <slamer@slamer.ru>
 * @author Дмитрий Кузьма <kouzma.d@gmail.com>
 * @version 1.0
 */
class User_Notification {
  public static $arrNotifications = null;
	public function __construct() {}
	
	/**
	 * Получает список оповещений по электронной почте
	 * 
	 */
	private function _getNotifications() {
		Service_Debug::setDebug();
		if (!self::$arrNotifications) {
			$objDB = Service_Database::instance();
			$stmt = "SELECT 
			  `notification`.`action`, `notification`.`subject_ru`, `notification`.`subject_en`, `notification`.`text_ru`, `notification`.`text_en` 
			  FROM `notification`";
			$arrNotifications = $objDB->select($stmt);
			self::$arrNotifications = Service_ArrayConverter::makeKeyArrayFromMultyArray($arrNotifications, 'action');
	  }
		return self::$arrNotifications;
		
	}
	
	/**
	 * Возвращаем начало письма
	 * 
	 * @param mixed $hello - Вступительный заголовок, если false, то брать стандартный
	 */
  private function _mailHello($hello = false) {
  	$language = Service_Translate::getLang();
  	$arrNotifications = $this->_getNotifications();
  	if ($hello === false) $hello = $arrNotifications['hello']['text_' . $language];
    $text = '<html>		
<table width="600" cellspacing="0" align="left" style="border-collapse: separate; font-family: Arial, Helvetica; font-size: 13px;">
<!-- header -->
<tr>
	<td width="600" height="8" style="border-top:1px solid #135D9D; border-bottom:1px solid #171819; background:#045398;"></td>
</tr>
<tr>
	<td height="80" width="600" bgcolor="#f0f0f0" style="background:url(cid:bg.png) repeat-x #F0F0F0;border:1px solid #d3d5d7; border-top:0;">
		<table width="600" height="80" cellspacing="0">
			<tr>
				<td width="30"></td>
				<td style="vertical-align:middle;" width="500"><a href="http://hotels.ru"><img border="0" src="cid:logo.png" /></a></td>
				<td style="vertical-align:middle;" width="20"><a href="http://vk.com/hotels"><img border="0" src="cid:vk.png" /></a></td>
				<td style="vertical-align:middle;" width="20"><a href="http://facebook.com/hotels.ru"><img border="0" src="cid:fb.png" /></a></td>
				<td width="10"></td>
			</tr>
		</table>
	</td>
</tr>
<!-- content -->
<tr>
	<td width="600" style="border-left:1px solid #d3d5d7;border-right:1px solid #d3d5d7;">
		<div style="padding:10px 20px">';
    if ($hello) $text .= '<h3 style="margin:10px 0px 15px 0px;">' . $hello . '</h3>';
    return $text;
  }

  private function _mailEnd($end = false, $opposite = false) {
  	$language = Service_Translate::getLang();
  	$arrNotifications = $this->_getNotifications();
  	if ($end === false) $end = $arrNotifications['end']['text_' . $language];
  	$end = str_replace('[site]', SITE_NAME, $end);
  	$end = str_replace('[url]', W_FULLPATH, $end);
  	
  	$text = $end ? $end : '';
  	if ($opposite) Service_Translate::setLang($language == 'ru' ? 'en' : 'ru');
  	$language = Service_Translate::getLang();
  	$text .= '</div>
		</td>
	</tr>
	<!-- footer -->
	<tr style="vertical-align:middle;">
		<td height="68" width="600" bgcolor="#f2f6e8" style="border:1px solid #d3d5d7;">
			<table width="600" cellspacing="0">
				<tr valign="bottom">
					<td width="30"></td>'  .
					($language == 'ru' && !$opposite ? '<td width="190"><b>' .  Service_Translate::getText('Бесплатно по России') . '</b></td>' : '') .
					'<td width="190"><b>' . Service_Translate::getText('Санкт-Петербург') . '</b></td>
					<td width="190"><b>' . Service_Translate::getText('Москва') . '</b></td>' .
					(($language == 'en' || $opposite) ? '<td width="190"></td>' : '') .
				'</tr>
				<tr valign="top">
					<td></td>' . 
    			($language == 'ru' && !$opposite ? '<td><font size="4"><b>8 800 555-09-21</b></font></td>' : '') .
					'<td><font size="4"><b>' . ($language == 'ru' && !$opposite ? '8' : '+7') . ' 812 309-57-60</b></font></td>
					<td><font size="4"><b>' . ($language == 'ru' && !$opposite ? '8' : '+7') . ' 495 505-63-25</b></font></td>' .
					(($language == 'en' || $opposite) ? '<td></td>' : '') .
				'</tr>
			</table>
		</td>
	</tr>
</table></html>';
		if ($opposite) Service_Translate::setLang($language == 'ru' ? 'en' : 'ru');			
		return $text;
  }
  
  private function _send($strEMail, $subject, $text, $hello = false, $msgType = 'default', $end = false, $opposite = false, $attachFile = null) {
  	//echo $text;
  	$text = $this->_cssText($text);
    $m = new Service_Amail( 
    	$strEMail, 
			$subject,
			///self::_mailHello($hello) . $text . self::_mailEnd($end, $opposite),                    
    		$text,
			"From: " . EMAIL_FROM . "\n",
			$msgType  
		);
		//$m->msgType = $msgType;
		//$m->file(IMAGES . 'mail/bg.png');
		//$m->file(IMAGES . 'mail/vk.png');
		//$m->file(IMAGES . 'mail/fb.png');
		//$m->file(IMAGES . 'mail/twitter.png');
		//$m->file(IMAGES . 'mail/logo.png');
		//if ($attachFile !== null && file_exists($attachFile) && is_file($attachFile)) {
		//	$m->file($attachFile);	
		//}
    return $m->send();
  }
  
  /**
   * Оформляем теги и классы в стилях, так чтобы понимал почтовый клиент
   * 
   * @param string $text - Текст письма
   * 
   * @return string - Оформленный текст письма
   */
  private function _cssText($text) {
  	$text = str_replace('<h3>', '<div class="header"><h2>', $text);
  	$text = str_replace('</h3>', '</h2></div>', $text);
  	$text = str_replace('<h4>', '<h4 style="font-size:16px; margin: 15px 0 0 0;">', $text);
  	$text = str_replace('<hr />', '<hr style="height:1px; margin: 10px 0; border: 0; background: #ccc;" />', $text);
  	$text = str_replace('<p>', '<p style="color:#000000; font-family: Arial, Helvetica; margin:3px 0; padding:0px;">', $text);
  	$text = str_replace('class="grey"', 'style="color: grey; font-size: 11px;"', $text);
  	$text = str_replace('<div class="header"><h2>', '<div style="padding:5px 10px;background:#e9f2fb;margin-top:20px;"><h2 style="margin:0px;font-size:20px;">', $text);
  	$text = str_replace('<div class="block"', '<div style="padding:0 10px;"', $text);
  	$text = str_replace('<div class="', '<div style="color:#000000; font-family: Arial, Helvetica;margin:3px 0;" class="', $text);
  	return $text;
  }

  /**
   * Метод уведомляет пользователя о его регистрации
   *
   * @param string $strEMail
   * @param string $login
   * @param string $pass
   */
  public function newAccount($strEMail, $login, $pass) {
  	preg_match('#\<(.+)\>#', $strEMail, $arrMatches);
  	$eMail = (isset($arrMatches[1]) ? $arrMatches[1] : $strEMail);
  	
    $arrNotifications = $this->_getNotifications();
    $language = Service_Translate::getLang();
    $subject = "[" . SITE_NAME . "] " . $arrNotifications['new_account']['subject_' . $language];
    $text = $arrNotifications['new_account']['text_' . $language];
    $code = Service_Generate::generateApproveCode($strEMail, $login); 
    $confirmationLink = W_FULLPATH . 'auth/approve/' . $code . '/' . $strEMail;
    $text = str_replace('[site]', SITE_NAME, $text);
    $text = str_replace('[email]', $eMail, $text);
  	$text = str_replace('[login]', $login, $text);
  	$text = str_replace('[pass]', $pass, $text);
  	$text = str_replace('[url]', $confirmationLink, $text);
    
  	return $this->_send($strEMail, $subject, $text, false, 'new_account');
  }

  /**
   * Метод уведомляет пользователя о создании для него нового аккаунта
   *
   * @param string $strEMail
   * @param string $login
   * @param string $pass
   */
  public function createAccount($strEMail, $login, $pass) {
  	preg_match('#\<(.+)\>#', $strEMail, $arrMatches);
  	$eMail = (isset($arrMatches[1]) ? $arrMatches[1] : $strEMail);
  	
    $arrNotifications = $this->_getNotifications();
    $language = Service_Translate::getLang();
    $subject = "[" . SITE_NAME . "] " . $arrNotifications['create_account']['subject_' . $language];
    $text = $arrNotifications['create_account']['text_' . $language];
    
    $code = Service_Generate::generateApproveCode($eMail, $login); 
    $confirmationLink = W_FULLPATH . 'auth/approve/' . $code . '/' . $eMail;
    $text = str_replace('[site]', SITE_NAME, $text);
  	$text = str_replace('[email]', $eMail, $text);
  	$text = str_replace('[login]', $login, $text);
  	$text = str_replace('[pass]', $pass, $text);
  	$text = str_replace('[url]', $confirmationLink, $text);
    
  	return $this->_send($strEMail, $subject, $text, false, 'create_account');
  }

  /**
   * Метод уведомляет гостиницу о создании для него нового аккаунта для экстранета
   *
   * @param string $strEMail
   * @param string $login
   * @param string $pass
   */
  public function createAccountForHotel($strEMail, $login, $pass) {
  	
    $arrNotifications = $this->_getNotifications();
    $language = Service_Translate::getLang();
    $subject = "[" . SITE_NAME . "] " . $arrNotifications['create_account_for_hotel']['subject_' . $language];
    $text = $arrNotifications['create_account_for_hotel']['text_' . $language];
    
    $code = Service_Generate::generateApproveCode($strEMail, $login); 
    $confirmationLink = W_FULLPATH . 'auth/approve/' . $code . '/' . $strEMail;
    $text = str_replace('[site]', SITE_NAME, $text);
  	$text = str_replace('[email]', $strEMail, $text);
  	$text = str_replace('[login]', $login, $text);
  	$text = str_replace('[pass]', $pass, $text);
  	$text = str_replace('[url]', $confirmationLink, $text);
    
  	$this->_send('contract@hotels.ru', $subject, $text, false, 'account_for_hotel');
  	$this->_send('irina@hotels.ru', $subject, $text, false, 'account_for_hotel');
  	return $this->_send($strEMail, $subject, $text, false, 'account_for_hotel');
  }
  
  /**
   * Метод уведомляет гостиницу о том, что на соответствующий аккаунт была добавлена гостиница
   *
   * @param string $strEMail
   * @param string $hotelName
   */
  public function addHotelToExtranetAccount($strEMail, $hotelName) {
    $arrNotifications = $this->_getNotifications();
    $language = Service_Translate::getLang();
    $subject = "[" . SITE_NAME . "] " . $arrNotifications['add_hotel_to_extranet_account']['subject_' . $language];
    $text = $arrNotifications['add_hotel_to_extranet_account']['text_' . $language];
    
    $text = str_replace('[site]', SITE_NAME, $text);
  	$text = str_replace('[email]', $strEMail, $text);
  	$text = str_replace('[hotel_name]', $hotelName, $text);
    
  	$this->_send('contract@hotels.ru', $subject, $text, false, 'add_hotel_for_account');
  	$this->_send('irina@hotels.ru', $subject, $text, false, 'add_hotel_for_account');
  	return $this->_send($strEMail, $subject, $text, false, 'add_hotel_for_account');
  }

  
  /**
   * Оповещает пользователя о создании ему нового пароля
   *
   * @param string $strEMail
   */
  public function recovery($strEMail, $pass) {
    $action = 'recovery';
    $language = Service_Translate::getLang();
  	$arrNotifications = $this->_getNotifications();
    $subject = "[" . SITE_NAME . "] " . $arrNotifications[$action]['subject_' . $language];
    $text = $arrNotifications[$action]['text_' . $language];

    $text = str_replace('[site]', SITE_NAME, $text);
  	$text = str_replace('[pass]', $pass, $text);
    
  	return $this->_send($strEMail, $subject, $text, false, 'recovery');
  }
  
  /**
   * Оповещает пользователя о новом заказе через Booking
   * 
   * @param string $strEMail - Электронная почта
   * @param string $action - Название оповещения для выбора из БД
   * @param Booking $objBooking - Заказ
   * @param Country $objCountry - Страна пользователя
   * @param BaseHotel $objHotel - Отель
   * @param array $arrBookingInfo - Информация по бронированию
   * @param array $arrCity - Город отеля
   * @param array $arrRooms - Комнаты отеля
   * @param array $arrMealTypes - Типы питания
   */
  public function booking($strEMail, $action, Booking $objBooking, Country $objCountry, BaseHotel $objHotel, array $arrBookingInfo, array $arrCity, array $arrRooms, array $arrMealTypes) {
    $language = Service_Translate::getLang();

    $arrNotifications = $this->_getNotifications();
    $subject = "[" . SITE_NAME . "] " . $arrNotifications[$action]['subject_' . $language];
    $text = $arrNotifications[$action]['text_' . $language];
	  $objViewBooking = new View_Booking();
    $info = $objViewBooking->getBookInfo($objBooking, $objCountry, $objHotel, $arrCity, $arrRooms, $arrBookingInfo, $arrMealTypes);
    $cancellationLink = $objViewBooking->getBookCancellationLink($objBooking);
    
    $text = str_replace('[site]', '<a href="' . W_FULLPATH . '">' . SITE_NAME . '</a>', $text);
    $text = str_replace(array('[hotel_link]', '[hotel_url]'), '<a href="' . View_Hotel::getUrl($objHotel->tableFields, true) . '">' . View_Hotel::getName($objHotel->tableFields) . '</a>', $text);
    $text = str_replace('[url]', '<a class="grey" href="' . W_FULLPATH . Service_Translate::getLangForUrl() . '/cancellation.htm?e_mail=' . $objBooking->getField('e_mail') . '&id=' . $objBooking->getField('id') . '">' . Service_Translate::getText('Отмена бронирования') . '</a>', $text);
  	$text = str_replace('[id]', $objBooking->getField('id'), $text);
  	$text = str_replace('[booking]', $objBooking->getField('id'), $text);
  	$text = str_replace('[pincode]', $objBooking->getField('pincode'), $text);
  	$text = str_replace('[info]', $info, $text);
  	$text = str_replace('[cancellation]', $cancellationLink, $text);
  	$subject = str_replace('[id]', $objBooking->getField('id'), $subject);
  	
  	// Записываем текст подтверждения в БД, чтобы потом можно было повторно отправить
  	$objBooking->updateField('our_notification_' . $language, Service_Escape::absolutelyEscapeStringSavingHtml($text));  	
  	$objBooking->updateField('our_notification_subject_' . $language, $subject);  	
  	
  	return $this->_send($strEMail, $subject, $text, false, $action);
  }
  
	/**
	 * Оповещает наш отель о новом заказе
	 *  
	 * @param Booking $objBooking - Бронирование 
	 * @param Country $objCountry - Страна
	 * @param OurHotel $objHotel - Отель
	 * @param array $arrBookingInfo - Данные по блокам
	 * @param array $arrCity - Город
	 * @param array $arrRooms - Комнаты
	 * @param array $arrMealTypes - Типы питания
	 */
  public function bookingToHotel(Booking $objBooking, Country $objCountry, OurHotel $objOurHotel, array $arrBookingInfo, array $arrCity, array $arrRooms, array $arrMealTypes) {
    $language = Service_Translate::getLang();
		$action = 'booking_to_hotel';
    $arrNotifications = $this->_getNotifications();
    $subject = "[" . SITE_NAME . "] " . $arrNotifications[$action]['subject_' . $language];
    $text = $arrNotifications[$action]['text_' . $language];
	  $objViewBooking = new View_Booking();
    $info = $objViewBooking->getHotelBookInfo($objBooking, $objCountry, $objOurHotel, $arrCity, $arrRooms, $arrBookingInfo, $arrMealTypes);
    
    $text = str_replace('[site]', SITE_NAME, $text);
  	$text = str_replace('[info]', $info, $text);
  	$text = str_replace('[link]', W_HOTEL_ADMIN_FULLPATH . 'bookings/?work_hotel=' . $objOurHotel->id, $text);
	  $subject = str_replace('[id]', $objBooking->getField('id'), $subject);
  	
  	// Записываем текст подтверждения в БД, чтобы потом можно было повторно отправить
  	$objBooking->updateField('our_notification_' . $language, Service_Escape::absolutelyEscapeStringSavingHtml($text));  	
  	$objBooking->updateField('our_notification_subject_' . $language, $subject);  	
  	$eMail = $this->makeNotifyEmails($objOurHotel);
  	
  	//$this->_send('slamer86@gmail.com', $subject, $text, 'Здравствуйте, уважаемые коллеги!', $action);
  	
  	$this->_send('info@hotels.ru', $subject, $text, 'Здравствуйте, уважаемые коллеги!', $action);
  	return $this->_send($eMail, $subject, $text, 'Здравствуйте, уважаемые коллеги!', $action);
  }
  
  /**
   * Повторно оповещает пользователя о заказе
   *
   * @param Booking $objBooking - Объект бронирования
   */
  public function bookingRepeat($eMail, Booking $objBooking) {    
		$arrLangs = array('ru', 'en');
		foreach ($arrLangs as $lang) {
			if ($objBooking->getField('our_notification_' . $lang)) {
				$this->_send($eMail, $objBooking->getField('our_notification_subject_' . $lang), $objBooking->getField('our_notification_' . $lang), false, 'booking_repeat');
			}
		}
  }
  
  /**
   * Оповещает пользователя об отмене заказа
   *
   * @param string $strEMail - Электронный адрес пользователя
   * @param Booking $objBooking - Бронирование
   * @param BaseHotel $objHotel - Отель
   */
  public function cancellation($strEMail, Booking $objBooking, BaseHotel $objHotel) {
    $language = Service_Translate::getLang();
    $action = 'cancellation';

    $arrNotifications = $this->_getNotifications();
    $subject = "[" . SITE_NAME . "] " . $arrNotifications[$action]['subject_' . $language];
    $text = $arrNotifications[$action]['text_' . $language];
	  $objViewBooking = new View_Booking();
	  $cancellationInfo = $objViewBooking->getCancellationInfo($objBooking, $objHotel);

	  $text = str_replace('[id]', $objBooking->getField('id'), $text);
	  $text = str_replace('[info]', $cancellationInfo, $text);
  	$subject = str_replace('[id]', $objBooking->getField('id'), $subject);

  	return $this->_send($strEMail, $subject, $text, false, 'cancellation');
  }
  
  /**
   * Оповещает отель об отмене заказа
   * 
   * @param Booking $objBooking - Бронирование
   * @param OurHotel $objOurHotel - Наш отель
   */
  public function cancellationToHotel(Booking $objBooking, OurHotel $objOurHotel) {
    $language = Service_Translate::getLang();
    $action = 'cancellation_to_hotel';

    $arrNotifications = $this->_getNotifications();
    $subject = "[" . SITE_NAME . "] " . $arrNotifications[$action]['subject_' . $language];
    $text = $arrNotifications[$action]['text_' . $language];
	  $cancellationCharge = $objBooking->getCancellationCharge();

	  $text = str_replace('[id]', $objBooking->getField('id'), $text);
	  $text = str_replace('[charge]', $cancellationCharge, $text);
  	$subject = str_replace('[id]', $objBooking->getField('id'), $subject);
		$eMail = $this->makeNotifyEmails($objOurHotel);
		
  	return $this->_send($eMail, $subject, $text, 'Внимание, уважаемые коллеги!', 'cancellation_to_hotel');
  }
   
  /**
   * Оповещает администратора о новом сообщения со страницы "Контакты"
   *
   * @param array $arrFeedback - массив с данными
   */
  public function feedback($arrFeedback) {
    $subject = "[" . SITE_NAME . "] Новый feedback";
    $text = '<br />';
    foreach ($arrFeedback as $key => $value) {
    	$text .= str_replace('_', ' ', Service_Function::utf8_first_to_upper($key));
    	$text .= ': ' . $value . '<br />';
    }
  	return $this->_send('szperevozki@gmail.com', $subject, $text);
  }
  
  /**
   * Оповещает администратора о новой заявки из блока "Заказать-звонок"
   *
   * @param array $arrFeedback - массив с данными
   */
  public function callOrder($arrFeedback) {
  	$subject = "[" . SITE_NAME . "] Заказ звонка";
  	$text = '<br />';
  	foreach ($arrFeedback as $key => $value) {
  		$text .= str_replace('_', ' ', Service_Function::utf8_first_to_upper($key));
  		$text .= ': ' . $value . '<br />';
  	}
  	return $this->_send('szperevozki@gmail.com', $subject, $text);
  }
  
  /**
   * Оповещает администратора о новом фидбэке
   *
   * @param array $arrFeedback - массив с данными
   */
  public function groupBooking($arrBooking) {
    $subject = "[" . SITE_NAME . "] Групповой заказ";
    $text = '<br />';
    foreach ($arrBooking as $key => $value) {
    	$text .= str_replace('_', ' ', Service_Function::utf8_first_to_upper($key));
    	$text .= ': ' . $value . '<br />';
    }
  	return $this->_send('spb@hotels.ru', $subject, $text);
  }
  
  /**
   * Оповещает администратора о предлоежениях о сотрудничестве
   *
   * @param array $arrData - массив с данными
   */
  public function offertHotel($arrData) {
    $subject = "[" . SITE_NAME . "] Предложения сотрудничества";
    $text = '<br />';
    foreach ($arrData as $key => $value) {
    	$text .= str_replace('_', ' ', Service_Function::utf8_first_to_upper($key));
    	$text .= ': ' . ($key == 'comment' ? str_replace("\n", "<br>", $value) : $value) . '<br />';
    }
  	$this->_send('kouzma.d@gmail.com', $subject, $text);
  	return $this->_send('contract@hotels.ru', $subject, $text);
  }  
  
  /**
   * Оповещает администратора о предлоежениях о сотрудничестве
   *
   * @param array $arrFeedback - массив с данными
   */
  public function careers($arrData) {
    $subject = "[" . SITE_NAME . "] Отклик на вакансию";
    $text = '<br />';
    foreach ($arrData as $key => $value) {
    	$text .= str_replace('_', ' ', Service_Function::utf8_first_to_upper($key));
    	$text .= ': ' . str_replace("\n", "<br>", $value) . '<br />';
    }
  	$this->_send('kouzma.d@gmail.com', $subject, $text);
  	$this->_send('slamer86@gmail.com', $subject, $text);
  	$this->_send('usakonza@gmail.com', $subject, $text);
  	$this->_send('astrzn@gmail.com', $subject, $text);
  }  
  /**
   * Оповещает администратора о заказе с другой формой оплаты
   *
   * @param array $arrBooking - массив с данными
   */
  public function bookingNonCreditCard(array $arrBooking, BaseHotel $objHotel, array $arrBlocks, array $arrMealTypes) {
  	Service_Debug::setDebug();
  	$language = Service_Translate::getLang();
		$objCountry = new Country($arrBooking['country_code']);
		$objCountryDest = new Country($objHotel->getField('country_code'));
		$objCityDest = new City($objHotel->getField('ID_city'));
		$arrBlockIds = array();
		$people = 0;
		foreach ($arrBooking['Room'] as $arrRoom) {
			$blockIds = explode('_', $arrRoom['ID_block']);
			$arrBlockIds[] = $blockIds[0];
			$people += $arrRoom['guest_qty'];
		}
		$subject = "[" . SITE_NAME . "] Заказ без кредитной карты";
    $text = '<br />';
    $text .= '<h2>Информация</h2>';
    $text .= '<p>Фамилия Имя: ' . $arrBooking['booker_last_name'] . ' ' . $arrBooking['booker_first_name'] . '</p>';
    $text .= '<p>E-Mail: ' . $arrBooking['e_mail'] . '</p>';
    $text .= '<p>Тип оплаты: ' . ($arrBooking['payment_type'] == 'Another' ? $arrBooking['other_payment_type'] : $arrBooking['payment_type']) . '</p>';
    $text .= '<h2>Адрес</h2>';
    $text .= '<p>Телефон: ' . $arrBooking['home_phone'] . '</p>';
    $text .= '<p>Страна: ' . $objCountry->getField('country_name_ru') . '</p>';
    $text .= '<p>Город: ' . $arrBooking['city'] . '</p>';

    $text .= '<h2>Гостиница</h2>';
    $text .= '<p>Гостей: ' . $people . '</p>';
    $text .= '<p>Страна: ' . $objCountryDest->tableFields['country_name_ru'] . '</p>';
    $text .= '<p>Город: ' . $objCityDest->tableFields['city_name_ru'] . '</p>';
    $text .= '<p><a href="' . View_Hotel::getUrl($objHotel->tableFields, true) . '?date_arr=' . Service_Date::dateBDToHuman($arrBooking['date_arr']) . '&date_dep=' . Service_Date::dateBDToHuman($arrBooking['date_dep']) . '&rooms=' . $arrBooking['rooms'] . '&adult=' . $arrBooking['adult'] . '&children=' . $arrBooking['children'] . '">' . View_Hotel::getName($objHotel->tableFields) . '</a></p>';
    $text .= '<p>Дата заезда:'  . Service_Date::dateToRus($arrBooking['date_arr']) . '</p>';
    $text .= '<p>Дата выезда: ' . Service_Date::dateToRus($arrBooking['date_dep']) . '</p>';
    
    $text .= '<h2>Номера</h2>';
    $i = 0;
    foreach ($arrBooking['Room'] as $arrRoom) {
			$blockIds = explode('_', $arrRoom['ID_block']);
    	$text .= '<h3>Номер ' . ++$i . '</h3>';
    	$text .= '<p>Название: ' . $arrBlocks[$arrRoom['ID_block']]['name'];
    	if ($arrRoom['bb']) $text .= ' - ' . $arrMealTypes[$arrRoom['bb']]['meal_type_name_' . $language]; 
    	if ($arrRoom['free']) $text .= ' - бесплатная отмена бронирования'; 
    	if ($arrRoom['dr']) $text .= ' - требуется предоплата'; 
    	$text .= '</p>';
	    $text .= '<p>Фамилия Имя: ' . $arrRoom['guest_name'] . '</p>';
	    if ($arrRoom['smoking'] == 1) $text .= '<p>Для некурящих</p>';
	    if ($arrRoom['smoking'] == 2) $text .= '<p>Для курящих</p>';
	    $text .= '<p>Цена: ' . $arrRoom['price'] . ' ' . $arrRoom['currency'] . '</p>';
	    $text .=  '<p>Количество гостей: ' . $arrRoom['guest_qty'] . '</p>';
    }
  	return $this->_send('spb@hotels.ru', $subject, $text);
  }  
  /**
   * Оповещает администратора о заказе с другой формой оплаты
   *
   * @param array $arrBooking - массив с данными
   */
  public function ourBookingNonCreditCard(Booking $arrBooking, Hotel $objHotel) {
		$objCountry = new Country($arrBooking['country_code']);
		$objCountryDest = new Country($objHotel->getField('country_code'));
		$objCityDest = new City($objHotel->getField('ID_city'));
		$arrBlockIds = array();
		$people = 0;
		foreach ($arrBooking['Room'] as $arrRoom) {
			$blockIds = explode('_', $arrRoom['ID_block']);
			$arrBlockIds[] = $blockIds[0];
			$people += $arrRoom['guest_qty'];
		}
		$objRoom = new OurRoom();
  	$arrRooms = $objRoom->getRoomsByIds($arrBlockIds);	
  	$arrRooms = Service_ArrayConverter::makeKeyArrayFromMultyArray($arrRooms, 'ID_our_room');
    $subject = "[" . SITE_NAME . "] Заказ без кредитной карты";
    $text = '<br />';
    $text .= '<h2>Информация</h2>';
    $text .= '<p>Фамилия Имя: ' . $arrBooking['booker_last_name'] . ' ' . $arrBooking['booker_first_name'] . '</p>';
    $text .= '<p>E-Mail: ' . $arrBooking['e_mail'] . '</p>';
    $text .= '<p>Тип оплаты: ' . ($arrBooking['payment_type'] == 'Another' ? $arrBooking['other_payment_type'] : $arrBooking['payment_type']) . '</p>';
    $text .= '<h2>Адрес</h2>';
    $text .= '<p>Телефон: ' . $arrBooking['home_phone'] . '</p>';
    $text .= '<p>Страна: ' . $objCountry->getField('country_name_ru') . '</p>';
    $text .= '<p>Город: ' . $arrBooking['city'] . '</p>';

    $text .= '<h2>Гостиница</h2>';
    $text .= '<p>Гостей: ' . $people . '</p>';
    $text .= '<p>Страна: ' . $objCountryDest->tableFields['country_name_ru'] . '</p>';
    $text .= '<p>Город: ' . $objCityDest->tableFields['city_name_ru'] . '</p>';
    $text .= '<p><a href="' . View_Hotel::getUrl($objHotel->tableFields, true) . '?date_arr=' . Service_Date::dateBDToHuman($arrBooking['date_arr']) . '&date_dep=' . Service_Date::dateBDToHuman($arrBooking['date_dep']) . '&rooms=' . $arrBooking['rooms'] . '&adult=' . $arrBooking['adult'] . '&children=' . $arrBooking['children'] . '">' . View_Hotel::getName($objHotel->tableFields) . '</a></p>';
    $text .= '<p>Дата заезда:'  . Service_Date::dateToRus($arrBooking['date_arr']) . '</p>';
    $text .= '<p>Дата выезда: ' . Service_Date::dateToRus($arrBooking['date_dep']) . '</p>';
    
    $text .= '<h2>Номера</h2>';
    $i = 0;
    foreach ($arrBooking['Room'] as $arrRoom) {
			$blockIds = explode('_', $arrRoom['ID_block']);
    	$text .= '<h3>Номер ' . ++$i . '</h3>';
    	$text .= '<p>Название: ' . $arrRooms[$blockIds[0]]['room_name_ru'];
    	if ($arrRoom['bb']) $text .= ' - завтрак'; 
    	if ($arrRoom['free']) $text .= ' - бесплатная отмена бронирования'; 
    	if ($arrRoom['dr']) $text .= ' - требуется предоплата'; 
    	$text .= '</p>';
	    $text .= '<p>Фамилия Имя: ' . $arrRoom['guest_name'] . '</p>';
	    if ($arrRoom['smoking'] == 1) $text .= '<p>Для некурящих</p>';
	    if ($arrRoom['smoking'] == 2) $text .= '<p>Для курящих</p>';
	    $text .= '<p>Цена: ' . $arrRoom['price'] . ' ' . $arrRoom['currency'] . '</p>';
	    $text .=  '<p>Количество гостей: ' . $arrRoom['guest_qty'] . '</p>';
    }
  	return $this->_send('spb@hotels.ru', $subject, $text);
  }  

	/**
	 * Оповещает администратора о том что отель хочет опубликоваться
	 * 
	 * @param OurHotel $objOurHotel - объект отеля
	 */  
  public function checkHotel(OurHotel $objOurHotel, array $arrHotelNames) {
    $subject = "[" . SITE_NAME . "] Заявка на проверку отеля";
    $text = '<br />';
    $text .= '<p>Заявка на проверку отеля "' . View_OurHotel::getName($objOurHotel->tableFields) . '"</p>';
    $text .= '<p>Ссылка <a href="' . W_HOTEL_ADMIN_FULLPATH . 'status/?work_hotel=' . $objOurHotel->id . '">' . W_FULLPATH . 'hms/status/?work_hotel=' . $objOurHotel->id . '</a></p>';
    $text .= '<p>Город: ' . View_City::getName($arrHotelNames) . '</p>';
    $text .= '<p><a href="' . View_OurHotel::getUrl($objOurHotel->tableFields, true) . '">Гостиница на сайте</a></p>';
    
    
  	$this->_send('contract@hotels.ru', $subject, $text);
  	return $this->_send('irina@hotels.ru', $subject, $text);
  }    

	/**
	 * Оповещает нашего администратора о том что пользователь запросил изменения 
	 * 
	 * @param BookingChange $objBookingChange - Объект изменения в бронировании
	 * @param Booking $objBooking - Объект бронирования
	 */  
  public function changeRequest(BookingChange $objBookingChange, Booking $objBooking) {
    $subject = "[" . SITE_NAME . "] Заявка на изменение бронирования";
    $text = '<p>Заявка на изменение бронирования #' . $objBookingChange->getField('ID_booking') . '<p>';
    $text .= '<p>Ссылка <a href="' . W_FULLPATH . 'cms/bookings/one/' . $objBookingChange->getField('ID_booking') . '/#changes">' . W_FULLPATH . 'cms/bookings/one/' . $objBookingChange->getField('ID_booking') . '/#changes</a></p>';
    if ($objBooking->getField('is_our') && $objBookingChange->getField('change_type') == 'card') {
    	$text .= '<p>Сообщение об изменении кредитки отправлено в отель</p>';
    }
    
  	return $this->_send('spb@hotels.ru', $subject, $text);
  }  

	/**
	 * Оповещает администратора отеля о том что пользователь запросил изменения 
	 * 
	 * @param BookingChange $objBookingChange - Объект изменения в бронировании
	 * @param Booking $objBooking - Объект бронирования
	 * @param OurHotel $objHotel - Объект отеля
	 */  
  public function changeRequestToHotel(BookingChange $objBookingChange, Booking $objBooking, OurHotel $objOurHotel) {
  	switch ($objBookingChange->getField('change_type')) {
  		case 'card':
  			$subject = '[' . SITE_NAME . '] Пользователь изменил кредитку в бронировании #' . $objBookingChange->getField('ID_booking');
  			break;
  		default: return false;
  	}
    $text = '<br />';
    $text .= 'Заявка на изменение бронирования #' . $objBookingChange->getField('ID_booking') . '<br />';
    $text .= 'Ссылка <a href="' . W_HOTEL_ADMIN_FULLPATH . 'bookings/?ID_work_hotel=' . $objBooking->getField('ID_hotel') . '#' . $objBookingChange->getField('ID_booking') . '">Перейти к бронированию</a>';
    
    $eMail = self::makeNotifyEmails($objOurHotel);
  	return $this->_send($eMail, $subject, $text);
  }  
    
	/**
	 * Оповещает владельца отеля о том что отель опубликован
	 * 
	 * @param OurHotel $objOurHotel - объект отеля
	 */  
  public function hotelApprove(OurHotel $objOurHotel) {
  	$arrNotifications = $this->_getNotifications();
    $language = Service_Translate::getLang();
    $subject = "[" . SITE_NAME . "] " . $arrNotifications['hotel_approve']['subject_' . $language];
    $text = $arrNotifications['hotel_approve']['text_' . $language];
    
    $text = str_replace('[site]', SITE_NAME, $text);
  	$text = str_replace('[name]', View_OurHotel::getName($objOurHotel->tableFields), $text);
  	$text = str_replace('[link]', '<a href="' . W_HOTEL_ADMIN_FULLPATH . '">' . W_HOTEL_ADMIN_FULLPATH . '</a>', $text);
  	$text = str_replace('[site_link]', '<a href="' . View_OurHotel::getUrl($objOurHotel->tableFields, true) . '">' . View_OurHotel::getUrl($objOurHotel->tableFields, true) . '</a>', $text);
  	
  	$eMail = $this->makeNotifyEmails($objOurHotel);
  	
  	return $this->_send($eMail, $subject, $text, false, 'hotel_approve');
  }    
	/**
	 * Оповещает владельца отеля о том что отелю отказано в публикации
	 * 
	 * @param OurHotel $objOurHotel - объект отеля
	 */  
  public function hotelReject(OurHotel $objOurHotel) {
  	$arrNotifications = $this->_getNotifications();
    $language = Service_Translate::getLang();
    $subject = "[" . SITE_NAME . "] " . $arrNotifications['hotel_reject']['subject_' . $language];
    $text = $arrNotifications['hotel_reject']['text_' . $language];
    
    $text = str_replace('[site]', SITE_NAME, $text);
  	$text = str_replace('[name]', View_OurHotel::getName($objOurHotel->tableFields), $text);
  	$text = str_replace('[link]', '<a href="' . W_HOTEL_ADMIN_FULLPATH . '">' . W_HOTEL_ADMIN_FULLPATH . '</a>', $text);
  	$text = str_replace('[comment]', $objOurHotel->getField('comment'), $text);
    
  	$eMail = $this->makeNotifyEmails($objOurHotel);
  	
  	return $this->_send($eMail, $subject, $text, false, 'hotel_reject');
  }    
  
  
  /**
   * Оповещает пользователя о новом заказе через Booking
   *
   * @param string $strEMail - адрес электронной почты, на который будет выслано соответствующее письмо.
   * @param Booking $objBooking - объект заказа, относящегося к письму
   */
  public function confirmFromBooking($strEMail, Booking $objBooking, Country $objCountry, BaseHotel $objHotel, array $arrCity, array $arrRooms, array $arrMealTypes, $opposite = false) {
  	
    $action = 'voucher';
    $language = Service_Translate::getLang();
  	$arrNotifications = $this->_getNotifications();
    $subject = "[" . SITE_NAME . "] " . $arrNotifications[$action]['subject_' . $language];
    $text = $arrNotifications[$action]['text_' . $language];
    $objViewBooking = new View_Booking();
    
    $voucherLanguage = $objHotel->getField('country_code') == 'ru' ? 'ru' : 'en';
    
    //echo $objBooking->getField('book_info_' . $voucherLanguage);
    //echo Service_Function::utf8_substr(str_replace('&#39;', "'", htmlspecialchars_decode(str_replace(array('*'), array('"'), $objBooking->getField('book_info_' . $voucherLanguage)))), 0, 1850);
    if ($objBooking->getField('book_info_' . $voucherLanguage)) $arrBookingInfo = Service_ArrayConverter::arrayStrReplace('!!!', '"', unserialize(str_replace('&#39;', "'", htmlspecialchars_decode(str_replace(array('*'), array('"'), $objBooking->getField('book_info_' . $voucherLanguage))))));
    else $arrBookingInfo = $objBooking->makeArrBookingInfo();
    $info = $objViewBooking->getBookVoucher($objBooking, $objCountry, $objHotel, $arrCity, $arrRooms, $arrBookingInfo, $arrMealTypes);
    $cancellationLink = $objViewBooking->getBookCancellationLink($objBooking);
    
    $peopleName = '';    
    if (!empty($objBooking->tableFields['booker_first_name'])) $peopleName .= $objBooking->getField('booker_first_name') . " ";
    if (!empty($objBooking->tableFields['booker_last_name'])) $peopleName .= $objBooking->getField('booker_last_name');
    
     $text = str_replace('[site]', '<a href="' . W_FULLPATH . '">' . SITE_NAME . '</a>', $text);
    $text = str_replace('[hotel_name]', View_Hotel::getName($objHotel->tableFields), $text);
    $text = str_replace('[id]', $objBooking->getField('id'), $text);
    $text = str_replace('[info]', $info, $text);
    $text = str_replace('[cancellation_link]', $cancellationLink, $text);
  	$subject = str_replace('[id]', $objBooking->getField('id'), $subject);
  	$subject = $this->userWillSeeItForAdmin($strEMail, $subject);
  	$emailToSend = $peopleName . ' <' . $strEMail . '>';
  	return $this->_send($emailToSend, $subject, $text, '', 'voucher', '', $opposite);
  }
  
  /**
   * Оповещает пользователя об его незаезде
   *
   * @param string $strEMail - адрес электронной почты, на который будет выслано соответствующее письмо.
   * @param Booking $objBooking - объект заказа, относящегося к письму
   * @param Hotel $objHotel - объект гостиницы, по которому сделан заказ
   */
  public function noShow($strEMail, Booking $objBooking, Hotel $objHotel) {
    $language = Service_Translate::getLang();
    $action = 'no_show';
  	$arrNotifications = $this->_getNotifications();
    $subject = "[" . SITE_NAME . "] " . $arrNotifications[$action]['subject_' . $language];
    $text = $arrNotifications[$action]['text_' . $language];
    
    $objViewBooking = new View_Booking();
    $objExchange = Service_Exchange::instance();
    
    $currencyCode = $objBooking->getField('b_com_cancellation_currency_code');
    $cancellationCurrencyPrice = $objBooking->getField('b_com_cancellation_cost');
		$objExchange->setCurrency($currencyCode);
		$price = $objExchange->getPrice($cancellationCurrencyPrice, $currencyCode, 2);
		if ($currencyCode != 'EUR') {
			$objExchange->setCurrency('EUR');
			$price .= ' ('. $objExchange->getPrice($cancellationCurrencyPrice, $currencyCode, 2) . ')';
		}
		$peopleName = '';
		if (!empty($objBooking->tableFields['booker_first_name'])) $peopleName .= $objBooking->getField('booker_first_name') . " ";
		if (!empty($objBooking->tableFields['booker_last_name'])) $peopleName .= $objBooking->getField('booker_last_name');

    $text = str_replace('[site]', SITE_NAME, $text);
    $text = str_replace('[id]', $objBooking->getField('id'), $text);
    $text = str_replace('[fio]', $objBooking->getField('booker_first_name') . '&nbsp;' . $objBooking->getField('booker_last_name'), $text);
  	 $text = str_replace('[hotel_name]', View_Hotel::getName($objHotel->tableFields), $text);
  	$text = str_replace('[hotel_base_info]', $objViewBooking->getBookingBaseInfo($objBooking, $objHotel), $text);	
  	$text = str_replace('[hotel_detail]', $objViewBooking->getDetailInfo($objBooking, $objHotel), $text);
  	$text = str_replace('[hotel_contacts]', $objViewBooking->getBookingHotelContacts($objBooking, $objHotel), $text);	
  	$text = str_replace('[cancellation_price]', $price, $text);	
  	$subject = str_replace('[id]', $objBooking->getField('id'), $subject);
  	$subject = $this->userWillSeeItForAdmin($strEMail, $subject);
  	return $this->_send($strEMail, $subject, $text, Service_Translate::getText('Уважаемый/ая', $peopleName), 'no_show');
  }
  
  /**
   * Оповещает пользователя об его раннем отъезде
   *
   * @param string $strEMail - адрес электронной почты, на который будет выслано соответствующее письмо.
   * @param Booking $objBooking - объект заказа, относящегося к письму
   * @param Hotel $objHotel - объект гостиницы, по которому сделан заказ
   */
  public function earlyDeparture($strEMail, Booking $objBooking, Hotel $objHotel) {
    $language = Service_Translate::getLang();
    $action = 'early_departure';
  	$arrNotifications = $this->_getNotifications();
    $subject = "[" . SITE_NAME . "] " . $arrNotifications[$action]['subject_' . $language];
    $text = $arrNotifications[$action]['text_' . $language];
    
    $objViewBooking = new View_Booking();
		$peopleName = '';
		if (!empty($objBooking->tableFields['booker_first_name'])) $peopleName .= $objBooking->getField('booker_first_name') . " ";
		if (!empty($objBooking->tableFields['booker_last_name'])) $peopleName .= $objBooking->getField('booker_last_name');

    $text = str_replace('[site]', SITE_NAME, $text);
    $text = str_replace('[id]', $objBooking->getField('id'), $text);
    $text = str_replace('[fio]', $objBooking->getField('booker_first_name') . '&nbsp;' . $objBooking->getField('booker_last_name'), $text);
  	$text = str_replace('[hotel_name]', View_Hotel::getName($objHotel->tableFields), $text);
  	$text = str_replace('[hotel_base_info]', $objViewBooking->getBookingBaseInfo($objBooking, $objHotel), $text);	
  	$text = str_replace('[hotel_detail]', $objViewBooking->getDetailInfo($objBooking, $objHotel), $text);
  	$text = str_replace('[hotel_contacts]', $objViewBooking->getBookingHotelContacts($objBooking, $objHotel), $text);	
  	$text = str_replace('[actual_days]', $objBooking->getField('actual_days'), $text);	
  	$subject = str_replace('[id]', $objBooking->getField('id'), $subject);
  	$subject = $this->userWillSeeItForAdmin($strEMail, $subject);
  	return $this->_send($strEMail, $subject, $text, Service_Translate::getText('Уважаемый/ая', $peopleName), 'early_departure');
  }
  
  /**
   * Оповещает пользователя об отмене его заказа
   *
   * @param string $strEMail - адрес электронной почты, на который будет выслано соответствующее письмо.
   * @param Booking $objBooking - объект заказа, относящегося к письму
   * @param Hotel $objHotel - объект гостиницы, по которому сделан заказ
   */
  public function cancellationFromBookingCom($strEMail, Booking $objBooking, Hotel $objHotel) {
    $language = Service_Translate::getLang();
    $action = 'cancellation_from_booking_com';
  	$arrNotifications = $this->_getNotifications();
    $subject = "[" . SITE_NAME . "] " . $arrNotifications[$action]['subject_' . $language];
    $text = $arrNotifications[$action]['text_' . $language];
    
    $objViewBooking = new View_Booking();
    $objExchange = Service_Exchange::instance();
   
    $currencyCode = $objBooking->getField('b_com_cancellation_currency_code');
    if (empty($currencyCode)) $currencyCode = $objBooking->getField('b_com_currency_code');
    if (empty($currencyCode)) $currencyCode = 'EUR';
    $cancellationCurrencyPrice = intval($objBooking->getField('b_com_cancellation_cost'));
    
		//$objExchange->setCurrency($currencyCode);
		$price = $cancellationCurrencyPrice . ' ' . $currencyCode;
		if ($currencyCode != 'EUR') {
			$objExchange->setCurrency('EUR');
			$price .= ' ('. $objExchange->getPrice($cancellationCurrencyPrice, $currencyCode, 2) . ')';
		}		
		$peopleName = '';
		if (!empty($objBooking->tableFields['booker_first_name'])) $peopleName .= $objBooking->getField('booker_first_name') . " ";
		if (!empty($objBooking->tableFields['booker_last_name'])) $peopleName .= $objBooking->getField('booker_last_name');
		
    $text = str_replace('[site]', SITE_NAME, $text);
    $text = str_replace('[id]', $objBooking->getField('id'), $text);
    $text = str_replace('[hotel_name]', View_Hotel::getName($objHotel->tableFields), $text);
  	$text = str_replace('[hotel_base_info]', $objViewBooking->getBookingBaseInfo($objBooking, $objHotel), $text);	
  	$text = str_replace('[hotel_detail]', $objViewBooking->getDetailInfo($objBooking, $objHotel), $text);
  	$text = str_replace('[hotel_contacts]', $objViewBooking->getBookingHotelContacts($objBooking, $objHotel), $text);	
  	$text = str_replace('[cancellation_price]', $price, $text);
  	$text = str_replace('[cancel_comment]', $objViewBooking->getCancelReason($objBooking), $text);
  	$subject = str_replace('[id]', $objBooking->getField('id'), $subject);
  	$subject = $this->userWillSeeItForAdmin($strEMail, $subject);
  	return $this->_send($strEMail, $subject, $text, Service_Translate::getText('Уважаемый/ая', $peopleName), 'cancellation_from_booking');
  }
  
  /**
   * Оповещает пользователя о том, что его кредитка заполнена неверно
   *
   * @param string $strEMail - адрес электронной почты, на который будет выслано соответствующее письмо.
   * @param Booking $objBooking - объект заказа, относящегося к письму
   * @param Hotel $objHotel - объект гостиницы, по которому сделан заказ
   * @param boolean $isExpired -  Карта просрочена (true), либо заполнена неверно (false)
   */
  public function wrongCreditCard($strEMail, Booking $objBooking, Hotel $objHotel, $isExpired  = false) {
    $language = Service_Translate::getLang();
    $action = 'wrong_credit_card';
  	$arrNotifications = $this->_getNotifications();
    $subject = "[" . SITE_NAME . "] " . $arrNotifications[$action]['subject_' . $language];
    $text = $arrNotifications[$action]['text_' . $language];
    
    $objViewBooking = new View_Booking();
    $objExchange = Service_Exchange::instance();
    $peopleName = '';
    
    if ($isExpired) $wrongText = 'Вероятно, истек срок действия кредитной карты.';
    else $wrongText = 'Вероятно, указаны неверные данные карты.';
    
    if (!empty($objBooking->tableFields['booker_first_name'])) $peopleName .= $objBooking->getField('booker_first_name') . " ";
    if (!empty($objBooking->tableFields['booker_last_name'])) $peopleName .= $objBooking->getField('booker_last_name');
    
    $text = str_replace('[site]', SITE_NAME, $text);
    $text = str_replace('[id]', $objBooking->getField('id'), $text);
    $text = str_replace('[hotel_name]', View_Hotel::getName($objHotel->tableFields), $text);
    $text = str_replace('[wrong_text]', Service_Translate::getText($wrongText), $text);
    $subject = str_replace('[id]', $objBooking->getField('id'), $subject);
    $subject = $this->userWillSeeItForAdmin($strEMail, $subject);
  	return $this->_send($strEMail, $subject, $text, Service_Translate::getText('Уважаемый/ая', $peopleName), 'wrong_credit_card');
  }
  /**
   * Письмо необычной плохой кредитной карты
   *
   * @param string $strEMail - адрес электронной почты, на который будет выслано соответствующее письмо.
   * @param Booking $objBooking - объект заказа, относящегося к письму
   * @param Hotel $objHotel - объект гостиницы, по которому сделан заказ
   */
  
  public function wrongCreditCardTo18($strEMail, Booking $objBooking, Hotel $objHotel) {
  	$language = Service_Translate::getLang();
  	$action = 'wrong_credit_card_to_18';
  	$arrNotifications = $this->_getNotifications();
  	$subject = "[" . SITE_NAME . "] " . $arrNotifications[$action]['subject_' . $language];
  	$text = $arrNotifications[$action]['text_' . $language];
  
  	$objViewBooking = new View_Booking();
  	$objExchange = Service_Exchange::instance();
  	$peopleName = '';
  
  	if (!empty($objBooking->tableFields['booker_first_name'])) $peopleName .= $objBooking->getField('booker_first_name') . " ";
  	if (!empty($objBooking->tableFields['booker_last_name'])) $peopleName .= $objBooking->getField('booker_last_name');
  
  	$text = str_replace('[site]', SITE_NAME, $text);
  	$text = str_replace('[id]', $objBooking->getField('id'), $text);
  	$text = str_replace('[hotel_name]', View_Hotel::getName($objHotel->tableFields), $text);
  	$subject = str_replace('[id]', $objBooking->getField('id'), $subject);
  	$subject = $this->userWillSeeItForAdmin($strEMail, $subject);
  	return $this->_send($strEMail, $subject, $text, Service_Translate::getText('Уважаемый/ая', $peopleName), 'wrong_credit_card_to_18');
  }
  
  /**
   * Формирует тему письма, для админов, что пользователь будет видеть это
   * 
   * @param string $eMail - eMail для проверки письма на соответствие админу
   * @param string $subject - тема письма
   */
  public function userWillSeeItForAdmin($eMail, $subject) {
  	Service_Debug::setDebug();
  	if (in_array($eMail, array('dmkouzma@gmail.com', 'slamer86@gmail.com', 'sheykhanov@gmail.com', 'spb@hotels.ru', 'info@hotels.ru'))) {
  		return 'Это будет видеть user: ' . $subject;
  	}
  	else return $subject;
  	
  }

  
  /**
   * Оповещает админов о важных проблемах
   * 
   * @param string $subject - Тема письма
   * @param string $text - Текст письма
   */
  public function adminMail($subject, $text) {
    if (DOMAIN == 'hotels.ru') {
     	$m = new Service_Amail(
    		'slamer86@gmail.com, kouzma.d@gmail.com', 
				$subject,
				$text,                    
				"From: " . EMAIL_FROM . "\n"
			);
		  $m->send();	
    }
  }
  
  /**
   * Создаем список E-Mail'ов для отправки
   * 
   * @param OurHotel $objOurHotel - Отель
   * 
   * @return string - Список мыл с пользователем через запятую
   */
  public function makeNotifyEmails(OurHotel $objOurHotel) {
  	Service_Debug::setDebug();
  	$arrNotifyEmails = explode(',', $objOurHotel->getField('notify_e_mail'));
  	$i = 0;
  	$eMail = '';
  	foreach ($arrNotifyEmails as $arrNotifyEmail) {
  		if ($i++) $eMail .= ', ';
  		$eMail .= $objOurHotel->getField('contact_person') . ' <' . trim($arrNotifyEmail) . '>';
  	}
  	return $eMail;
  }
  
	/**
	 * Высылает владельцам отеля счет
	 * 
	 * @param OurHotel $objOurHotel - объект отеля
	 * @param string $yearMonth - год и месяц для отчета
	 * 
	 * @throws Exception
	 */  
  public function hotelMonthBill(OurHotel $objOurHotel, $yearMonth ) {
  	$arrNotifications = $this->_getNotifications();
    $language = Service_Translate::getLang();
    $filePath = FILES . 'bills/' . $objOurHotel->id . $yearMonth . '.pdf';
    if (!file_exists($filePath) || !is_file($filePath)) throw new Exception('Файл счета не существует'); 
    $subject = "[" . SITE_NAME . "] " . $arrNotifications['hotel_month_bill']['subject_' . $language];
    $text = $arrNotifications['hotel_month_bill']['text_' . $language];
    
    
    $text = str_replace('[site]', SITE_NAME, $text);
  	$text = str_replace('[name]', View_OurHotel::getName($objOurHotel->tableFields), $text);
  	$text = str_replace('[link]', '<a href="' . W_HOTEL_ADMIN_FULLPATH . '">' . W_HOTEL_ADMIN_FULLPATH . '</a>', $text);
  	$text = str_replace('[site_link]', '<a href="' . View_OurHotel::getUrl($objOurHotel->tableFields, true) . '">' . View_OurHotel::getUrl($objOurHotel->tableFields, true) . '</a>', $text);
  	
  	$eMail = $this->makeNotifyEmails($objOurHotel);
  	$this->_send($eMail, $subject, $text, false, 'hotel_month_bill', false, false, $filePath);
  	$eMail = "dmkouzma@gmail.com, irina@hotels.ru, contract@hotels.ru";
  	//$eMail = "dmkouzma@gmail.com, dmitri@kouzma.ru"; 
  	
  	return $this->_send($eMail, $subject, $text, false, 'hotel_month_bill', false, false, $filePath);
  } 
  
}
?>